package test.concurrent;

import java.util.concurrent.CountDownLatch;

/**
 * Created by guoyachao on 2018/7/2.
 */
public class CountDownLatchSimple {

    /**
     *  排队执行，当所有的线程1运行完后再运行线程2
     * @param args /NL
     */
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for(int i=0;i<5;i++){
            Thread thread = new Thread(new FirstCountDownLatch(countDownLatch));
            thread.start();
        }
        for(int i=0;i<5;i++){
            Thread thread = new Thread(new SecondCountDownLatch(countDownLatch));
            thread.start();
        }
        System.out.println("First线程将count减到1，Second线程统一挂起,main线程在减一，Second线程运行");
        countDownLatch.countDown();
    }
    static class FirstCountDownLatch implements Runnable {

        private CountDownLatch countDownLatch;

        FirstCountDownLatch(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }

        public void run() {
            System.out.println("FirstCountDownLatch run");
            countDownLatch.countDown();
        }
    }
    static class SecondCountDownLatch implements Runnable {

        private CountDownLatch countDownLatch;

        SecondCountDownLatch(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("SecondCountDownLatch run");
        }
    }

}
